package com.pvdnc.riru.appinjector.nuwa;

import com.pvdnc.riru.appinjector.nuwa.mirror.R_BaseDexClassLoader;
import com.pvdnc.riru.appinjector.nuwa.mirror.R_PathList;

import java.lang.reflect.Field;

public class Nuwa {
    public static void injectDexAtFirst(ClassLoader target,ClassLoader source) throws Exception {

        Object baseDexElements = getDexElements(getPathList(target));
        Object newDexElements = getDexElements(getPathList(source));
        Object allDexElements = ArrayUtils.combineArray(newDexElements, baseDexElements);
        Object pathList = getPathList(target);
        //更新 ReflectionUtils.setField(pathList, pathList.getClass(), "dexElements", allDexElements);
        Class<?> cls=pathList.getClass();
        Field field=cls.getDeclaredField("dexElements");
        field.setAccessible(true);
        field.set(pathList,allDexElements);
    }

    public static void removeDex(ClassLoader all,ClassLoader sub) throws Exception {

        Object baseDexElements = getDexElements(getPathList(all));
        Object subDexElements = getDexElements(getPathList(sub));
        Object allDexElements = ArrayUtils.removeSubArray(baseDexElements,subDexElements);

        Object pathList = getPathList(all);
        //更新 ReflectionUtils.setField(pathList, pathList.getClass(), "dexElements", allDexElements);
        R_PathList.dexElements.set(pathList,allDexElements);
    }

    private static Object getDexElements(Object pathList)
            throws IllegalArgumentException, IllegalAccessException {
        return R_PathList.dexElements.get(pathList);
    }

    private static Object getPathList(ClassLoader cl)
            throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        return R_BaseDexClassLoader.pathList.get(cl);
    }

}
